"""文件工具函数"""

import os
import shutil
from pathlib import Path
from typing import List, Optional, Tuple


def ensure_directory(path: Path) -> bool:
    """确保目录存在"""
    try:
        path.mkdir(parents=True, exist_ok=True)
        return True
    except Exception as e:
        print(f"创建目录失败: {e}")
        return False


def get_video_files(directory: Path, extensions: List[str] = None) -> List[Path]:
    """获取目录中的视频文件"""
    if extensions is None:
        extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.ts', '.m2ts']
    
    video_files = []
    
    try:
        for ext in extensions:
            video_files.extend(directory.glob(f"*{ext}"))
            video_files.extend(directory.glob(f"*{ext.upper()}"))
    except Exception as e:
        print(f"获取视频文件失败: {e}")
    
    return video_files


def get_file_size(file_path: Path) -> Optional[int]:
    """获取文件大小（字节）"""
    try:
        return file_path.stat().st_size
    except Exception:
        return None


def format_file_size(size_bytes: int) -> str:
    """格式化文件大小"""
    if size_bytes == 0:
        return "0 B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    while size_bytes >= 1024 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1
    
    return f"{size_bytes:.2f} {size_names[i]}"


def get_video_duration(file_path: Path) -> Optional[float]:
    """获取视频时长（秒）"""
    try:
        # 这里需要集成实际的视频时长获取逻辑
        # 可以使用OpenCV或FFmpeg
        return None
    except Exception:
        return None


def format_duration(seconds: float) -> str:
    """格式化时长"""
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    seconds = seconds % 60
    
    if hours > 0:
        return f"{hours:02d}:{minutes:02d}:{seconds:05.2f}"
    else:
        return f"{minutes:02d}:{seconds:05.2f}"


def copy_file_with_progress(src: Path, dst: Path, progress_callback=None) -> bool:
    """带进度回调的文件复制"""
    try:
        # 确保目标目录存在
        ensure_directory(dst.parent)
        
        # 获取文件大小
        total_size = get_file_size(src)
        if total_size is None:
            return False
        
        # 复制文件
        copied_size = 0
        with open(src, 'rb') as f_src, open(dst, 'wb') as f_dst:
            while True:
                chunk = f_src.read(64 * 1024)  # 64KB chunks
                if not chunk:
                    break
                
                f_dst.write(chunk)
                copied_size += len(chunk)
                
                # 调用进度回调
                if progress_callback:
                    progress = (copied_size / total_size) * 100
                    progress_callback(progress)
        
        return True
        
    except Exception as e:
        print(f"文件复制失败: {e}")
        return False


def safe_delete(file_path: Path) -> bool:
    """安全删除文件"""
    try:
        if file_path.exists():
            if file_path.is_file():
                file_path.unlink()
            else:
                shutil.rmtree(file_path)
        return True
    except Exception as e:
        print(f"删除文件失败: {e}")
        return False


def get_unique_filename(file_path: Path) -> Path:
    """获取唯一的文件名"""
    if not file_path.exists():
        return file_path
    
    stem = file_path.stem
    suffix = file_path.suffix
    parent = file_path.parent
    counter = 1
    
    while True:
        new_name = f"{stem}_{counter:03d}{suffix}"
        new_path = parent / new_name
        
        if not new_path.exists():
            return new_path
        
        counter += 1


def validate_video_file(file_path: Path) -> Tuple[bool, str]:
    """验证视频文件"""
    if not file_path.exists():
        return False, "文件不存在"
    
    if not file_path.is_file():
        return False, "不是有效的文件"
    
    # 检查文件扩展名
    video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.ts', '.m2ts']
    if file_path.suffix.lower() not in video_extensions:
        return False, "不支持的文件格式"
    
    # 检查文件大小
    file_size = get_file_size(file_path)
    if file_size is None or file_size == 0:
        return False, "文件大小为0或无法读取"
    
    return True, "文件有效"